<template>
  <div class="custom">
    <div style="display: flex; justify-content: space-between">
      <div>
        <el-button size="mini"
          type="primary"
          @click="addFromDialog = true"
          style="margin-bottom: 10px"
          >新增客户</el-button
        >
        <!-- 修改流水分红 -->
        <el-button size="mini"
          type="primary"
          @click="addFromDialog4 = true"
          style="margin-bottom: 10px"
        >
          分红设置
        </el-button>
      </div>

      <!-- 新增订单 -->

      <div>
        <el-input size="mini"
          style="width: 250px"
          v-model="company"
          clearable
          placeholder="按公司名,客户名,电话,地址查询"
          @change="getAllGoods"
        ></el-input>
		<el-button size="mini" @click="reset" v-debounce>重置</el-button>
        <!-- 搜索 -->
        <!--        <el-button
          icon="el-icon-search"
          circle
          style="margin-left: 20px"
          @click="likeEmployee()"
        ></el-button> -->

        <!-- <el-select
          v-model="receiptsStatusValue"
          style="width: 150px"
          placeholder="入库状态"
        >
          <el-option
            v-for="item in receiptsStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
        <!-- <el-button type="success" @click="receiptsStatusSelect">查询</el-button> -->
      </div>
    </div>

    <div class="goods-table">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
        height="100%"
      >
        <el-table-column prop="i" label="序号" width="50"> </el-table-column>
        <el-table-column prop="company" label="公司名称" fit width="180">
        </el-table-column>
        <el-table-column prop="customName" label="客户名称" fit width="80">
        </el-table-column>
        <el-table-column prop="phone" label="手机号" fit width="115">
        </el-table-column>
        <el-table-column prop="address" label="地址" fit width="200">
        </el-table-column>
        <el-table-column prop="demand" label="做板要求" fit width="200">
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="200">
        </el-table-column>
        <el-table-column label="操作" width="135" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="more(scope.row)">
				编辑
			</el-button>
			<el-divider direction="vertical"></el-divider>
            <el-button size="mini" type="text" @click="zhangdan(scope.row)">
				账单
			</el-button>
			<el-divider direction="vertical"></el-divider>
            <el-button size="mini" type="text" @click="deleteGoods(scope.row)">
				删除
			</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 修改分红 -->
    <el-dialog
      style="margin-top: 0"
      :visible.sync="addFromDialog4"
      width="50%"
      :show-close="false"
      title="分红设置"
    >
      <el-form
        :model="bonusInfo"
        :inline="true"
        ref="bonusInfo"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="绘图" prop="onePrice">
          <el-input
            type="text"
            v-model="bonusInfo.onePrice"
            placeholder="绘图"
          ></el-input>
        </el-form-item>
        <el-form-item label="切割" prop="twoPrice">
          <el-input
            type="text"
            v-model="bonusInfo.twoPrice"
            placeholder="切割"
          ></el-input>
        </el-form-item>
        <el-form-item label="装刀" prop="threePrice">
          <el-input
            type="text"
            v-model="bonusInfo.threePrice"
            placeholder="装刀"
          ></el-input>
        </el-form-item>
        <el-form-item label="装线" prop="fourPrice">
          <el-input
            type="text"
            v-model="bonusInfo.fourPrice"
            placeholder="装线"
          ></el-input>
        </el-form-item>
        <el-form-item label="打包" prop="five">
          <el-input
            type="text"
            v-model="bonusInfo.five"
            placeholder="打包"
          ></el-input>
        </el-form-item>
        <el-form-item label="附加费" prop="six">
          <el-input
            type="text"
            v-model="bonusInfo.six"
            placeholder="附加费"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateBon" v-debounce>保 存</el-button>
        <el-button @click="addFromDialog4 = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 账单 -->
    <el-dialog
      style="margin-top: 0"
      :visible.sync="addFromDialog3"
      width="80%"
      :show-close="false"
      title="账单"
    >
      <el-button type="success" size="mini" @click="print" v-debounce>打 印</el-button>
      <div id="printable-content" class="printable">
        <!-- 待打印的内容 -->
        <div style="text-align: center; font-size: 20px; font-weight: bold">
          浩泽数控设备有限公司销售单
        </div>
        <div
          style="
            display: flex;
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
            justify-content: space-between;
          "
        >
          <div>客户：{{ zhdan }}</div>
          <div style="margin-right: 50px">
            日期：{{ formatDate(new Date()) }}
          </div>
        </div>
        <el-table :data="dayinInfo" border style="width: 100%; margin: 20px">
          <el-table-column prop="versionNumber" label="版号" width="120">
          </el-table-column>
          <el-table-column prop="productName" label="产品名称" width="200">
          </el-table-column>
          <el-table-column prop="unit" label="单位" width="50">
          </el-table-column>
          <el-table-column prop="number" label="数量" width="50">
          </el-table-column>
          <el-table-column prop="price" label="金额(元)" width="100">
          </el-table-column>
          <el-table-column prop="punishment" label="备注" width="100">
          </el-table-column>
        </el-table>
        <div style="margin: 20px; margin-left: 70%">
          本单应收：{{ priceSum }}元
        </div>
        <div
          style="
            display: flex;
            justify-content: space-between;
            margin: 20px;
            margin-left: 100px;
            margin-right: 100px;
          "
        >
          <div>经手人：{{ jsr }}</div>
          <div>联系电话：{{ phone }}</div>
        </div>
      </div>
      我的账单
      <el-select v-model="days" @change="cxzd()" placeholder="请选择" 
		size="mini" style="width: 100px;">
        <el-option
          v-for="item in options4"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>

      经手人：
      <el-input size="mini" v-model="jsr" style="width: 100px" placeholder="经手人">
	  </el-input>
      联系电话：
      <el-input size="mini"
        v-model="phone"
        style="width: 150px"
        placeholder="联系电话"
      ></el-input>

      <span
        style="
          font-size: 16px;
          font-weight: bold;
          margin-left: 20px;
          color: red;
        "
        >总收入：{{ sumprice }}</span
      >

      <el-table
        :data="UserOrder"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        height="250"
      >
        <el-table-column type="selection" width="55"> </el-table-column>

        <el-table-column fixed prop="time" label="日期" width="200">
          <template slot-scope="scope">
            {{ formatDate(scope.row.time) }}
          </template>
        </el-table-column>
        <el-table-column prop="cusNum" label="序号" width="120">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="产品名称" width="120">
        </el-table-column>
        <el-table-column prop="versionNumber" label="版号" width="120">
        </el-table-column>
        <el-table-column prop="price" label="价格" width="120">
        </el-table-column>
        <el-table-column prop="isSend" label="是否发货" width="120">
        </el-table-column>
        <el-table-column prop="deliveryTime" label="交货时间" width="120">
        </el-table-column>
        <el-table-column prop="surPrice" label="附加费" width="120">
        </el-table-column>
        <el-table-column prop="head" label="负责人" width="120">
        </el-table-column>
        <el-table-column prop="count" label="备注" width="120">
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 查看更多 -->
    <el-dialog
      style="margin-top: 0"
      :visible.sync="addFromDialog2"
      width="60%"
      :show-close="false"
      title="编辑信息"
    >
      <el-form
        :model="genduo"
        :inline="true"
        ref="genduo"
        label-width="100px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <!-- 客户名称 -->
        <el-form-item label="公司名称：">
          <el-input
            type="text"
            v-model="genduo.company"
            placeholder="客户名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="客户名称：" prop="customName">
          <el-input
            type="text"
            v-model="genduo.customName"
            placeholder="客户名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="手机号：" prop="phone">
          <el-input
            type="text"
            v-model="genduo.phone"
            placeholder="手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="地址：" prop="address">
          <el-input
            type="text"
            v-model="genduo.address"
            placeholder="地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="做板要求：">
          <el-input
            type="text"
            v-model="genduo.demand"
            placeholder="做板要求"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            type="text"
            v-model="genduo.remark"
            placeholder="备注"
          ></el-input>
        </el-form-item>
      </el-form>

      <!-- //修改按钮，靠右边 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateOrders" v-debounce>保 存</el-button>
        <el-button @click="addFromDialog2 = false">取 消</el-button>
      </span>
      <!-- {{ genduo }} -->
    </el-dialog>

    <!-- 新增客户 -->
    <el-dialog
      style="margin-top: 0"
      :visible.sync="addFromDialog"
      width="60%"
      :show-close="false"
      :title="title"
    >
      <el-form
        :model="prudproducts"
        :inline="true"
        ref="prudproducts"
        label-width="100px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item label="公司名称：">
          <el-input
            type="text"
            v-model="prudproducts.company"
            placeholder="客户名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="客户名称：" prop="customName">
          <el-input
            type="text"
            v-model="prudproducts.customName"
            placeholder="客户名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="手机号：" prop="phone">
          <el-input
            type="text"
            v-model="prudproducts.phone"
            placeholder="手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="地址：" prop="address">
          <el-input
            type="text"
            v-model="prudproducts.address"
            placeholder="地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="做板要求：">
          <el-input
            type="text"
            v-model="prudproducts.demand"
            placeholder="做板要求"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            type="text"
            v-model="prudproducts.remark"
            placeholder="备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitaddEmployeeForm" v-debounce
          >确 定</el-button
        >
        <el-button @click="addFromDialog = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from "dayjs";
import {
  updateOrderStatus, //用户修改自己做的订单状态
  selectCustomByPage, //分页查询客户信息
  addCustom, //新增客户
  selectCustomByNickName, //模糊查询客户信息
  updateCustom, //修改客户信息
  deleteCustomById, //删除客户
  userNameDieOrderInfo, //用户账单
  updateBonus, //修改分红
  getBonus, //获取分红
  getCustomList, // 获取客户列表
} from "../../api/die.js";
export default {
  components: {},
  data() {
    return {
      bonusInfo: "",
      sumprice: 0, //总收入
      jsr: "张三",
      phone: "123456789",
      priceSum: 0, //总价
      dayinInfo: "",
      zhdan: "",
      days: -1,
      UserOrder: [],
      check1: false,
      check2: false,
      check3: false,
      check4: false,
      check5: false,
      //搜索框的值
      company: null,
      // 图片预览
      srcList: [],
      srcList2: [],
      //新增标题
      title: "新增客户",
      roleType: false,
      cover: "cover",
      // 显示表单
      addFromDialog: false,
      addFromDialog2: false,
      addFromDialog3: false,
      addFromDialog4: false,
      // 表格加载
      loading: false,
      //合同到期提醒
      dialogImageUrl: "",
      dialogVisible: false,
      genduo: "", //查看更多
      //新增订单数据
      prudproducts: {
        company: null,
        customName: null,
        phone: null,
        address: null,
        demand: null,
        remark: null,
      },
      tableData: [],
      //总数页
      total: 1,
      //是否发货
      SexCategory: [
        { value: 0, label: "男" },
        { value: 1, label: "女" },
      ],
      options4: [
        { value: -1, label: "全部" },
        { value: 1, label: "一天内" },
        { value: 7, label: "一周內" },
        { value: 30, label: "一个月内" },
        { value: 365, label: "一年内" },
      ],
      // 分页大小
      pageSize: 50,
      //记录当前页数
      currentPage: 1,
      //审核通过状态
      applyStatus: false,
      rules: {
        customName: [
          {
            required: true,
            message: "请输入客户名称",
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入电话号码",
            trigger: "blur",
          },
        ],
        address: [
          {
            required: true,
            message: "请输入地址",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    let userObject = JSON.parse(localStorage.getItem("userInfo"));
    if (userObject.roleId === "1") {
      this.roleType = true;
    }
    getBonus().then((res) => {
      if (res.code) {
        this.bonusInfo = res.data;
      } else {
        this.$message("获取分红失败");
      }
    });
    this.getAllGoods();
    // console.log("初始化时间:", dayjs())
    //通过入库名称搜索框查询
  },
  //超级管理员显示功能
  methods: {
    // 格式化时间
    formatDate(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, "0");
      const day = d.getDate().toString().padStart(2, "0");
      const hours = d.getHours().toString().padStart(2, "0");
      const minutes = d.getMinutes().toString().padStart(2, "0");
      const seconds = d.getSeconds().toString().padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

      // return `${year}-${month}-${day}`;
    },
    startTimeChange(value) {
      this.addEmployeeForm.startTime = dayjs(value).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      console.log("上架时间", dayjs(value).format("YYYY-MM-DD HH:mm:ss"));
    },
    endTimeChange(value) {
      this.addEmployeeForm.endTime = dayjs(value).format("YYYY-MM-DD HH:mm:ss");
      console.log("上架时间", dayjs(value).format("YYYY-MM-DD HH:mm:ss"));
    },
    userOrde() {},
    //用户修改自己做的订单状态
    stUpdate(ch) {
      let type = "";
      let status = "2";
      if (ch == "check1") {
        type = 1;
        if (this.check1) {
          status = "1";
        }
      } else if (ch == "check2") {
        type = 2;
        if (this.check2) {
          status = "1";
        }
      } else if (ch == "check3") {
        type = 3;
        if (this.check3) {
          status = "1";
        }
      } else if (ch == "check4") {
        type = 4;
        if (this.check4) {
          status = "1";
        }
      } else if (ch == "check5") {
        type = 5;
        if (this.check5) {
          status = "1";
        }
      }

      this.updcha(type, status);
    },

    print() {
      // 获取待打印的内容
      let printableContent =
        document.getElementById("printable-content").innerHTML;

      // 创建一个新的窗口, 要把之前的样式拿过来
      let printWindow = window.open(
        "",
        "PRINT",
        "width=800,height=600,top=100,left=100"
      );

      // 添加样式，使表头紧贴数据内容，并增加外边距和处理备注过长的问题
      let style = `
    <style>
      table {
        border-collapse: collapse;
        width: 100%;
        margin: 20px;
      }
      table, th, td {
        border: 1px solid black;
        padding: 4px; /* 减小padding */
        margin: 0; /* 去掉margin */
      }
      .remarks {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 150px; /* 根据需要调整最大宽度 */
      }
    </style>
  `;

      printWindow.document.write(
        "<html><head><title>账单</title>" + style + "</head><body>"
      );
      printWindow.document.write(printableContent);
      printWindow.document.write("</body></html>");
      printWindow.document.close();
      printWindow.print();
    },

    //账单
    zhangdan(item) {
      this.zhdan = item.customName;
      this.addFromDialog3 = true;
      this.cxzd();
    },

    cxzd() {
      userNameDieOrderInfo(this.zhdan, this.days).then((res) => {
        if (res.code) {
          //计算总收入金额
          this.sumprice = 0;
          for (let i = 0; i < res.data.dieOrderList.length; i++) {
            this.sumprice += res.data.dieOrderList[i].price;
          }
          this.UserOrder = res.data.dieOrderList;
        } else {
          this.$message("查询失败");
        }
      });
    },

    handleSelectionChange(val) {
      console.log(val);
      this.priceSum = 0;
      let arr = [];
      for (let i = 0; i < val.length; i++) {
        let obj = {
          versionNumber: val[i].versionNumber,
          productName: val[i].productName,
          price: val[i].price,
          unit: "块",
          number: 1,
          punishment: val[i].punishment,
        };
        this.priceSum += val[i].price;
        arr.push(obj);
      }
      this.dayinInfo = arr;
    },
    //删除用户
    deleteGoods(row) {
      this.$confirm("是否删除该用户", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //删除用户
          deleteCustomById(row.dieCustomId).then((data) => {
            if (data.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              //刷新数据
              this.getAllGoods();
            } else {
              this.$message({
                type: "error",
                message: "删除失败",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //修改分红
    updateBon() {
      updateBonus(this.bonusInfo).then((res) => {
        if (res.code) {
          this.$message("修改成功");
          this.addFromDialog4 = false;
        } else {
          this.$message("修改失败");
        }
      });
    },

    //修改用户
    updateOrders() {
      updateCustom(this.genduo).then((data) => {
        if (data.code == 200) {
          this.$message({
            type: "success",
            message: "修改成功",
          });
          //关闭弹窗
          this.addFromDialog2 = false;
          //刷新数据
          this.getAllGoods();
        } else {
          this.$message({
            type: "error",
            message: "修改失败",
          });
        }
      });
    },
    //查看更多
    more(row) {
      this.check1 = false;
      this.check2 = false;
      this.check3 = false;
      this.check4 = false;
      this.check5 = false;

      this.addFromDialog2 = true;
      this.genduo = row;
      //从本地拿到用户信息
      let user = localStorage.getItem("userInfo");
      let userObject = JSON.parse(user);
      let stOneArr = this.genduo.stOne
        ? this.genduo.stOne.split(",").filter((item) => item !== "")
        : [];
      let stTwoArr = this.genduo.stTwo
        ? this.genduo.stTwo.split(",").filter((item) => item !== "")
        : [];
      let stThreeArr = this.genduo.stThree
        ? this.genduo.stThree.split(",").filter((item) => item !== "")
        : [];
      let stFourArr = this.genduo.stFour
        ? this.genduo.stFour.split(",").filter((item) => item !== "")
        : [];
      let stFiveArr = this.genduo.stFive
        ? this.genduo.stFive.split(",").filter((item) => item !== "")
        : [];

      let optArr = [stOneArr, stTwoArr, stThreeArr, stFourArr, stFiveArr];

      for (let i = 0; i < optArr.length; i++) {
        for (let j = 0; j < optArr[i].length; j++) {
          if (optArr[i][j] == userObject.nickName) {
            switch (i) {
              case 0:
                this.check1 = true;
                break;
              case 1:
                this.check2 = true;
                break;
              case 2:
                this.check3 = true;
                break;
              case 3:
                this.check4 = true;
                break;
              case 4:
                this.check5 = true;
                break;
            }
          }
        }
      }
    },

    //用户修改
    updcha(type, status) {
      updateOrderStatus(this.genduo.customId, type, status).then((data) => {
        if (data.code) {
          this.$message({
            type: "success",
            message: "修改成功",
          });
          //刷新数据
          this.getAllGoods();
        } else {
          this.$message({
            type: "error",
            message: "修改失败",
          });
        }
      });
    },

    // 新增产品
    submitaddEmployeeForm() {
      addCustom(this.prudproducts).then((res) => {
        if (res.code) {
          this.$message("新增成功");
          this.addFromDialog = false;
          this.getAllGoods();
        } else {
          this.$message("新增失败");
        }
      });
      this.addFromDialog = false;
    },

    //模糊查询信息
    likeEmployee() {
      console.log("模糊查询");
      selectCustomByNickName(this.input).then((res) => {
        if (res.code) {
          this.tableData = res.data.data;
        } else {
          this.$message("查询失败");
        }
      });
    },

    //初始化图片
    imgstatus() {
      let url =
        "https://kris-k.oss-cn-hangzhou.aliyuncs.com/kris/c179093a-41b0-4c70-bc1f-6e5973f35c98-jia.png";
      this.imageUrl = url;
      this.imageUrl2 = url;
    },

    // 查询列表
    getAllGoods() {
      this.loading = true;
      const data = {
        company: this.company,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
      };
      getCustomList(data)
        .then((res) => {
          if (res.code === 200) {
            this.total = res.data.total;
            this.tableData = res.data.dieCustomDtoList.map((item, index) => {
              item.i = (this.currentPage - 1) * this.pageSize + index + 1;
              return item;
            });
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // pageSize变化
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getAllGoods();
    },
    // 页码变化
    handleCurrentChange(curPage) {
      this.currentPage = curPage;
      this.getAllGoods();
    },
	// 重置
	reset(){
		this.company = "";
		this.getAllGoods();
	}
  },
};
</script>

<style scoped>
	
	.custom{
		height: 100%;
	}
	
.page {
  text-align: center;
}

.nameBox {
  overflow: auto; /* 显示滚动条 */
  z-index: 99;
  margin-top: 5px;
  font-size: 12px;
  text-align: center;
  width: 205px;
  height: 170px;
  border-radius: 5px;
  background-color: #ffffff;
  box-shadow: 0 6px 10px rgba(0, 0, 0, 0.2);
  position: absolute;
}

/* 在普通视图中隐藏 */
.printable {
  display: none;
}

/* 在打印时显示 */
@media print {
  .printable {
    display: block;
  }
}

.goods-table {
  height: 94%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
}
.imgUrl {
  width: 100px;
  height: 100px;
  object-fit: cover; /* 保持原始宽高比，填充容器 */
}
.htimg {
  width: 150px;
  height: 150px;
  object-fit: cover; /* 保持原始宽高比，填充容器 */
}
</style>
